/*!
 * New Launch.
 * Date: 2015/12/29.
 * Copyright© 2014-2015 Vamaker All Rights Reserved.
 */
require([
    'jquery',
		'pageInit',
		'formValidator',
    'formAjax',
    'notification',
    'dateRange',
    'moment'
	], function ($, vamakerPage, formValidator, formAjax, VamOpMsg, DateRange, moment) {
  $(function () {
    var $dataFrm = $('#data-frm'),
        $submitBtn = $dataFrm.find('button[type="submit"]'),
        $operateBtn = $submitBtn.filter('.save-btn'),
        $operateType = $dataFrm.find('.operate-type'),
        $minTotalBudget = $dataFrm.find('.min-total-budget'),
        dateRange = new DateRange(),
        $rangeDateBtn = $('#range-date-btn'),
        $filterDateRange = $('#range-date'),
        /*****频次控制*****/
        $frequencyRangeDateBtn = $('#frequency-range-date-btn'),
        $frequencyFilterDate = $('#frequency-open-date'),
        $frequencyCtrl = $dataFrm.find('.frequency-control-type'),
        $unionFrequencyCtrl = $('#union_frequency_ctrl'),
        /*****频次控制*****/
        dataFieldRule, options, dataValidator;
      //投放时间选择
      dateRange.dateRange(
        $rangeDateBtn, {
          drops: "up",
          minDate: moment()
        }, function (start, end, label) {
          selectDate = start.format('YYYY-MM-DD') + ' - ' + end.format('YYYY-MM-DD');
          // console.log(selectDate);
          $filterDateRange.val(selectDate).trigger('blur');
      });
      //频次控制时间选择
      dateRange.dateRange(
        $frequencyRangeDateBtn, {
          drops: "up",
          singleDatePicker: true,
          minDate: moment(),
          startDate: $frequencyFilterDate.val(),
        }, function (start, end, label) {
          selectDate = start.format('YYYY-MM-DD');
          $frequencyFilterDate.val(selectDate).trigger('blur');
      });

      $submitBtn.on('click', function (evt) {
        var $me = $(this),
          operate = $me.data('operate'),
          operateTxt;
        operateTxt = '.' + operate + '-btn';
        $operateBtn = $submitBtn.filter(operateTxt);
        $operateType.val(operate);
      });

      $frequencyCtrl.on('change', function(){
        var $me = $(this),
            meVal = $me.val();
        if (meVal === '1') {
          $unionFrequencyCtrl.removeClass('hidden');
        } else {
          $unionFrequencyCtrl.addClass('hidden');
        }
      });

      function frequencyCheck(evt) {
        var $me = $(this),
        meVal = $me.val(),
        $errorBox = $me.next(),
        flag = true,
        msg = '';
        if ($me.attr('id') === 'frequency_upper_limit' && meVal === '') {
          msg = '<em class="checky-default-failure">' + VAM.j('Frequency upper limit cannot be empty') + '</em>';
          $errorBox.html(msg);

          if (!$errorBox.hasClass('frequency_err')) {
            $errorBox.addClass('frequency_err')
          }

        } else if (!!meVal && !/^\d+$/.test(meVal)) {
          msg = '<em class="checky-default-failure">' + VAM.j('Only integer number') + '</em>'
          $errorBox.html(msg);

          if (!$errorBox.hasClass('frequency_err')) {
            $errorBox.addClass('frequency_err')
          }

        } else {
          $errorBox.html('').removeClass('frequency_err');
        };
      }

      $('#frequency_upper_limit').on('blur', frequencyCheck);
      $('#frequency_lower_limit').on('blur', frequencyCheck);

      $dataFrm.find('input:checked').trigger('change');
      dataFieldRule = {
        launch_name:{
          rule:{
              required:{
                  message:VAM.j('Campaign name cannot be empty')
              }
          },
          messageContainer:'launch_name_err'
        },
        belong_campaign:{
          rule:{
              required:{
                  message:VAM.j('Belong campaign cannot be empty')
              }
          },
          messageContainer:'belong_campaign_err'
        },
        total_budget:{
          rule:{
              required:{
                message:VAM.j('Total Budget cannot be empty')
              },
              floatnumber:{
                message:VAM.j('Only float number')
              },
              minval:{
                param: parseFloat('0.01'),
                message:VAM.j('Enter a mininum of 0.01')
              },
              effectiveNumber:{
                message:VAM.j('Keep two decimal')
              },
          },
          messageContainer:'total_budget_err'
        },
        range_date: {
          rule: {
            required: {
              message: VAM.j('Time range cannot be empty')
            }
          },
          messageContainer: 'range_date_err'
        }
      };
      options = {
        submitOnSucceed: false,
        onvalidate: function(evt) {
          if (evt.resultList.length <= 0) {
              var $totalBudget = $('#total_budget'),
              $totalBudgetErr = $('#total_budget_err'),
              $frequencyTimesErr = $('#frequency_times_err'),
              $frequencyUpperLimit = $('#frequency_upper_limit'),
              $frequencyLowerLimit = $('#frequency_lower_limit'),
              minTotalBudget = parseFloat($minTotalBudget.text()),
              totalBudget = parseFloat($totalBudget.val());
              if (totalBudget < minTotalBudget) {
                  $totalBudgetErr.html('<em class="checky-default-failure">' + VAM.j('Total budget not below') + minTotalBudget + VAM.j('￥') + '</em>');
                  return;
              } else {
                  $totalBudgetErr.html('');
              };
              
              if ($frequencyCtrl.filter(':checked').val() === '1') {
                $frequencyUpperLimit.trigger('blur');
                $frequencyLowerLimit.trigger('blur');
                if ($('.frequency_err').length !== 0) {
                  return false;
                }
              };

              $dataFrm.ajaxSubmit({
                  beforeSubmit: function() {
                    $operateBtn.button('loading');
                  },
                  success: function (data) {
                    var next = $operateBtn.data('operate'),
                      $strategyType = $('.strategy_type'),
                      strategyType = $strategyType.filter(':checked').val();
                    $operateBtn.button('reset');
                    if (data.status === 'success') {
                        VamOpMsg.messager(data);
                        if (next === 'save-next' && strategyType === 'mobile') {
                          window.location.href = VAM.getVar('NEXT_MOBILE_URL') + '?campaignId=' + data.data.id;
                        } else if (next === 'save-next' && strategyType === 'pc') {
                          window.location.href = VAM.getVar('NEXT_PC_URL') + '?campaignId=' + data.data.id;
                        } else {
                          window.location.href = 'launch-list';
                        };
                    } else {
                        VamOpMsg.messager(data);
                    }
                  }
              });
          };
        }
      };
      formValidator.validate($dataFrm, dataFieldRule, options);
      dataValidator = formValidator.dataValidator;
      dataValidator.addRule('effectiveNumber',function(val, opt){
        return !!(val && /^\d+(\.\d{1,2})?$/.test(val));
      });
  });
});
